/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.nifi.processors.huawei.obs;

import org.apache.nifi.processors.huawei.credentials.provider.service.HuaweiCredentialsProviderControllerService;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.nifi.processors.huawei.common.PropertyDescriptors.*;


/**
 * Provides integration level testing with actual Huawei OBS resources for {@link ListOBSObject} and requires additional configuration and resources to work.
 * Because of the shared bucket, each test method stores objects into the same bucket, causing query confusion, so clearObjects is called after each method completes,
 * and sleep is forced for a second before TestRunner is executed to avoid the effects between methods.
 */
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ITListOBSObject extends AbstractOBSIT{
    @Test
    public void testSimpleList() throws IOException, InterruptedException {
        String[] putFiles = new String[]{"a","b/c","c/e","c/f","d/e"};
        putTestFile(putFiles);
        final TestRunner runner = initRunner(new ListOBSObject());
        runner.setValidateExpressionUsage(false);
        sleep();
        runner.run();
        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 5);
        sleep();
        // update
        putTestFile(putFiles);
        runner.run();

        // repeat the cycle to ensure that all new objects are listed
        // AbstractListProcessor.listByTrackingTimestamps
        sleep();
        runner.run();
        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 10);
        List<MockFlowFile>  flowFiles = runner.getFlowFilesForRelationship(ListOBSObject.REL_SUCCESS);
        flowFiles.get(0).assertAttributeEquals("filename", "a");
        flowFiles.get(1).assertAttributeEquals("filename", "b/c");
        flowFiles.get(2).assertAttributeEquals("filename", "c/e");
        flowFiles.get(3).assertAttributeEquals("filename", "c/f");
        flowFiles.get(4).assertAttributeEquals("filename", "d/e");
        clearObjects(putFiles);
    }

    @Test
    public void testRegionNotFound() throws IOException, InterruptedException {
        String[] putFiles = new String[]{"a","b/c","c/e","c/f","d/e"};

        putTestFile(putFiles);
        final TestRunner runner = initRunner(new ListOBSObject(), ENDPOINT);
        runner.setValidateExpressionUsage(false);
        sleep();
        runner.run();
        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 5);
        sleep();
        // update
        putTestFile(putFiles);
        runner.run();

        // repeat the cycle to ensure that all new objects are listed
        // AbstractListProcessor.listByTrackingTimestamps
        sleep();
        runner.run();
        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 10);
        List<MockFlowFile>  flowFiles = runner.getFlowFilesForRelationship(ListOBSObject.REL_SUCCESS);
        flowFiles.get(0).assertAttributeEquals("filename", "a");
        flowFiles.get(1).assertAttributeEquals("filename", "b/c");
        flowFiles.get(2).assertAttributeEquals("filename", "c/e");
        flowFiles.get(3).assertAttributeEquals("filename", "c/f");
        flowFiles.get(4).assertAttributeEquals("filename", "d/e");
        clearObjects(putFiles);
    }

    @Test
    public void testSimpleListUsingCredentialsProviderService() throws Throwable {
        String[] putFiles = new String[]{"a","b/c","d/e"};
        putTestFile(putFiles);
        final TestRunner runner = initRunner(new ListOBSObject());
        final HuaweiCredentialsProviderControllerService serviceImpl = new HuaweiCredentialsProviderControllerService();
        runner.addControllerService("huaweiCredentialsProvider", serviceImpl);
        runner.setProperty(serviceImpl, ACCESS_KEY, ak);
        runner.setProperty(serviceImpl, SECRET_KEY, sk);
        runner.enableControllerService(serviceImpl);
        runner.assertValid(serviceImpl);
        runner.setProperty(HUAWEI_CREDENTIALS_PROVIDER_SERVICE, "huaweiCredentialsProvider");
        runner.setValidateExpressionUsage(false);
        runner.run();
        // repeat the cycle to ensure that all new objects are listed
        // AbstractListProcessor.listByTrackingTimestamps
        sleep();
        runner.run();
        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 3);
        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ListOBSObject.REL_SUCCESS);
        flowFiles.get(0).assertAttributeEquals("filename", "a");
        flowFiles.get(1).assertAttributeEquals("filename", "b/c");
        flowFiles.get(2).assertAttributeEquals("filename", "d/e");
        clearObjects(putFiles);
    }

    @Test
    public void testSimpleListWithDelimiter() throws Throwable {
        String[] putFiles = new String[]{"dm1","dm2/c","dm2_/e"};
        putTestFile(putFiles);
        final TestRunner runner = initRunner(new ListOBSObject());
        runner.setProperty(DELIMITER, "2");
        sleep();
        runner.run();

        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 1);
        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ListOBSObject.REL_SUCCESS);
        flowFiles.get(0).assertAttributeEquals("filename", "dm1");
        clearObjects(putFiles);
    }

    @Test
    public void testSimpleListWithPrefixAndDelimiter() throws Throwable {
        String[] putFiles = new String[]{"tdm1","tdm2/c","tdm2_/e"};
        putTestFile(putFiles);
        final TestRunner runner = initRunner(new ListOBSObject());
        runner.setProperty(PREFIX, "t");
        runner.setProperty(DELIMITER, "1");
        sleep();
        runner.run();

        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 2);
        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ListOBSObject.REL_SUCCESS);
        flowFiles.get(0).assertAttributeEquals("filename", "tdm2/c");
        clearObjects(putFiles);
    }

    @Test
    public void testSimpleListWithPrefix() throws Throwable {
        String[] putFiles = new String[]{"a","bc","b/c","d/e"};
        putTestFile(putFiles);
        final TestRunner runner = initRunner(new ListOBSObject());
        runner.setProperty(PREFIX, "b");
        sleep();
        runner.run();

        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 2);
        List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ListOBSObject.REL_SUCCESS);
        flowFiles.get(0).assertAttributeEquals("filename", "bc");
        flowFiles.get(1).assertAttributeEquals("filename", "b/c");
        clearObjects(putFiles);
    }

    @Test
    public void testUserMetadataWritten() throws FileNotFoundException, InterruptedException {
        String key = "b/fileWithUserMetadata";
        Map<String, Object> userMetadata = new HashMap<>();
        userMetadata.put("dummy.metadata.1", "dummyvalue1");
        userMetadata.put("dummy.metadata.2", "dummyvalue2");
        putFileWithUserMetadata(key, getFileFromResourceName(SAMPLE_FILE_RESOURCE_NAME), userMetadata);
        final TestRunner runner = initRunner(new ListOBSObject());
        runner.setProperty(PREFIX, "b/");
        runner.setProperty(WRITE_USER_METADATA, "true");
        sleep();
        runner.run();

        runner.assertAllFlowFilesTransferred(ListOBSObject.REL_SUCCESS, 1);

        MockFlowFile flowFiles = runner.getFlowFilesForRelationship(ListOBSObject.REL_SUCCESS).get(0);
        flowFiles.assertAttributeEquals("filename", "b/fileWithUserMetadata");
        flowFiles.assertAttributeExists("obs.userMetadata.dummy.metadata.1");
        flowFiles.assertAttributeExists("obs.userMetadata.dummy.metadata.2");
        flowFiles.assertAttributeEquals("obs.userMetadata.dummy.metadata.1", "dummyvalue1");
        flowFiles.assertAttributeEquals("obs.userMetadata.dummy.metadata.2", "dummyvalue2");
        clearObjects(key);
    }
}
